package main

import (
	"flag"
	"log"
	"net/http"
	"time"

	"github.com/dgraph-io/badger/v4"
)

var (
	configFilePath string
)

func init() {
	flag.StringVar(&configFilePath, "config", "", "Path to the configuration file")
}

func main() {
	flag.Parse()

	// 加载配置
	config, err := loadConfig(configFilePath)
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// 打开 BadgerDB
	opts := badger.DefaultOptions(config.DataDir)
	opts.ValueLogFileSize = 256 * 1014 * 1024
	opts.ValueLogMaxEntries = 100000
	opts.NumGoroutines = 3
	opts.NumCompactors = 2
	opts.NumMemtables = 2
	db, err := badger.Open(opts)
	if err != nil {
		log.Fatalf("Failed to open BadgerDB: %v", err)
	}
	defer db.Close()

	// 定期运行垃圾回收任务
	go func() {
		for {
			time.Sleep(1 * time.Hour)    // 每 10 分钟运行一次
			err := db.RunValueLogGC(0.5) // 当已删除条目的比例达到 50% 时，进行垃圾回收
			if err != nil {
				log.Printf("Failed to run value log GC: %v", err)
			}
		}
	}()

	// 启动 HTTP 服务
	http.HandleFunc("/write", writeHandler(db, config))
	http.HandleFunc("/get", getHandler(db, config))
	http.HandleFunc("/get_prefix", getByPrefixHandler(db, config))
	http.HandleFunc("/delete", deleteHandler(db, config))
	http.HandleFunc("/batch_write", batchWriteHandler(db, config))
	http.HandleFunc("/batch_get", batchGetHandler(db, config))
	http.HandleFunc("/batch_delete", batchDeleteHandler(db, config))

	log.Printf("Server listening on port %d with data directory %s and log directory %s", config.Port, config.DataDir, config.LogDir)
	log.Fatal(http.ListenAndServe(config.Port, nil))
}
